Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

221
Views
What is the difference between "?" and "= null" in PHP function parameters

I was doing some research but wasn't able to find an answer (probably beacause I did not searched it right)

Consider this piece of code:

public function foo(?array $optionalParam);

And then this one:

public function foo(array $optionalParam = null);

What differs between them? Using PHPstorm I noticed that when I use the ?, it creates a PHPdoc and mark the variable type as type|null. But when I call the function without that argument, PHP screams on my face "you kidding me? where is $optionalParam". In the other side, I managed to use with no problems the =null option.

Sorry if this question is too simple, but i did not find any answers online.

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

First of all, the ? goes before the type, not after... other than this:

Using

public function foo(?array $optionalParam);

you are forced to pass something, that can be either null or an array, infact:

<?php
function foo(?array $optionalParam){
  echo "test";
}

foo(); // doesn't work
foo(null); // works
foo([]); // works

where instead using

public function foo(array $optionalParam = null);

will accept null, an array, or 0 parameters

<?php
function foo(array $optionalParam = null){
  echo "test";
}

foo(null); // works
foo(); // work
foo([]); // works
over 4 years ago · Santiago Trujillo Report

0

It's a PHP 7.1 feature called Nullable Types

Both of the lines you wrote are identical.

array ?$optionalParam : either an array or null

array $optionalParam = null : either an array or null

Tho using ? you'd still need to add the parameter when calling the function.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!